package com.andyage.util;

import java.io.IOException;


import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.Logger;
import org.dom4j.Document;   
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;   
import org.dom4j.Element; 

/**
 * 对接安迪公司使用的ihuyi
 * 验证码还是很快，这个需要满足模板，不然发送会失败
 * 您的手机验证码是：111111。如非本人操作请致电：15928978874。
 * @author liuyayun
 *
 */
public class SMSServerIhuyi {
	/**
	 * 短信发送服务器地址
	 */
	private static String url = MyConfig.SMSServerIhuyi_url;
	/**
	 * 账户
	 */
	private static String account = MyConfig.SMSServerIhuyi_account;
	/**
	 * 密码
	 */
	private static String password = MyConfig.SMSServerIhuyi_password;
	/**
	 * 日志打印
	 */
	private static Logger x_logger = Logger.getLogger(SMSServerIhuyi.class); 
	/**
	 * 发送短信，只能一条一条
	 * @param tel
	 * @param message
	 * @return
	 */
	public static boolean smsServer(String tel,String message)
	{
		boolean result = false;
		
		HttpClient client = new HttpClient(); 
		PostMethod method = new PostMethod(url); 
			
		//client.getParams().setContentCharset("GBK");		
		client.getParams().setContentCharset("UTF-8");
		method.setRequestHeader("ContentType","application/x-www-form-urlencoded;charset=UTF-8");

		
//		int mobile_code = (int)((Math.random()*9+1)*100000);

		//System.out.println(mobile);
		
//	    String content = new String("您的验证码是：" + mobile_code + "。请不要把验证码泄露给其他人。"); 

		NameValuePair[] data = {//提交短信
			    new NameValuePair("account", account), 
			    new NameValuePair("password", password), //密码可以使用明文密码或使用32位MD5加密
			    //new NameValuePair("password", util.StringUtil.MD5Encode("密码")),
			    new NameValuePair("mobile", tel), 
			    new NameValuePair("content", message),
		};
		
		method.setRequestBody(data);		
		
		
		try {
			client.executeMethod(method);	
			
			String SubmitResult =method.getResponseBodyAsString();
					
			//System.out.println(SubmitResult);

			Document doc = DocumentHelper.parseText(SubmitResult); 
			Element root = doc.getRootElement();


			String code = root.elementText("code");	
			String msg = root.elementText("msg");	
			String smsid = root.elementText("smsid");	
			
			x_logger.info("code:"+code);
			x_logger.info("msg:"+msg);
			x_logger.info("smsid:"+smsid);
						
			 if("2".equals(code)){
				 x_logger.info("短信提交成功");
				result = true;
			}
			
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			x_logger.error(e);
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			x_logger.error(e);
			e.printStackTrace();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			x_logger.error(e);
			e.printStackTrace();
		}	
		
		return result;
	}
}
